package com.ruoyi.web.controller.tool;

import cn.hutool.json.JSONUtil;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.domain.CodeEntity;
import com.tbit.openapi.business.sms.model.SmsReq;
import com.tbit.openapi.business.sms.model.SmsResp;
import com.tbit.openapi.business.sms.service.SmsService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.xml.bind.SchemaOutputResolver;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

@Slf4j
@Component
public class CaptchCodeUtils {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SmsService smsService;

    public AjaxResult sendCode(String phone) {
        SysUser sysUser = sysUserMapper.selectUserByUserName(phone);
        if (sysUser == null){
            return AjaxResult.error("该手机号未注册！请先注册后再登录");
        }
//        String host = "https://send.market.alicloudapi.com";
//        String path = "/sms/send";
//        String method = "POST";
//        String appcode = "92bece4a392045608184d128598be428";
//        Map<String, String> headers = new HashMap<String, String>();
//        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
//        headers.put("Authorization", "APPCODE " + appcode);
//        //根据API的要求，定义相对应的Content-Type
//        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//        Map<String, String> querys = new HashMap<String, String>();
//        Map<String, String> bodys = new HashMap<String, String>();
//        //随机生成6位数验证码
//        String code = String.valueOf((int) (Math.random() * 900000) + 100000);
//
//
//        bodys.put("content", "code:"+code);
//        bodys.put("templateid", "WW_023642vcrdtovwiciu");
//        bodys.put("mobile", phone);
//
//
//        try {
//
//            HttpResponse response = CodeHttpUtils.doPost(host, path, method, headers, querys, bodys);
//            log.debug("response status:{}",response.getStatusLine());
////            System.out.println(response.getEntity());
//            //获取response的body
//            HttpEntity responseEntity = response.getEntity();
//            CodeEntity codeEntity = JSONUtil.toBean(EntityUtils.toString(responseEntity), CodeEntity.class);
//            if ("OK".equals(codeEntity.getStatus())){
//                redisCache.setCacheObject(phone+"_code",  code);
//                redisCache.expireMinu(phone+"_code", 5);
//                return AjaxResult.success("验证码发送成功！");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return AjaxResult.error("验证码发送失败！");

        //        //随机生成6位数验证码
        String code = String.valueOf((int) (Math.random() * 900000) + 100000);

        SmsReq req = new SmsReq();
        req.setPhone(phone);
        req.setTemplateId(10482);
        Map<String, String> params = new HashMap<>();
        params.put("code", code);
        req.setParams(params);

        SmsResp resp = smsService.send(req);
        if (resp.getResult()) {
            redisCache.setCacheObject(phone+"_code",  code);
            redisCache.expireMinu(phone+"_code", 5);
            return AjaxResult.success("验证码发送成功！");
        } else {
            return AjaxResult.success("验证码发送失败！");
        }


//        String code = String.valueOf((int) (Math.random() * 900000) + 100000);
//        log.debug("验证码："+code);
//        //测试注册
//        redisCache.setCacheObject(phone+"_code",  code);
//        redisCache.expireMinu(phone+"_code", 5);
//        return AjaxResult.success("验证码发送成功！");

    }


    public  String checkCode(String phone, String code) {
        String redisCode = redisCache.getCacheObject(phone+"_code");
        log.debug("redisCode："+redisCode);
        if (redisCode == null){
            return "验证码已过期！";
        }
        if (!redisCode.equals(code)){
            return "验证码错误！";
        }
        return "OK";
    }
}